﻿using DzInfo.Tools;
using Kingdee.BOS;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;

namespace DzInfo.SerivesPlugin.Ronma
{
    [Description("校验销售出库单是否有下游单据：运费采购合同"), HotUpdate]
    public class VerifySalOutUnAudit : AbstractOperationServicePlugIn
    {
        public override void BeforeExecuteOperationTransaction(BeforeExecuteOperationTransaction e)
        {
            var obj = e.SelectedRows.Select(s => s.DataEntity).FirstOrDefault();
            if (obj != null)
            {
                string salNo = obj["BillNo"] == null ? "" : obj["BillNo"].ToString();
                DynamicObject val = obj["F_PXIA_Assistant"] as DynamicObject;
                string number = val == null ? "" : val["FNumber"].ToString();
                if (number != "JHFS02_SYS")
                {
                    if (!GetContract(this.Context, salNo).IsNullOrEmptyOrWhiteSpace())
                    {
                        IOperationResult operationResult = new OperationResult();
                        operationResult.OperateResult = new OperateResultCollection()
                        {
                            new OperateResult()
                            {
                                SuccessStatus = false,
                                Message = "已经生成运费采购合同，不允许反审核！合同单号为："+GetContract(this.Context, salNo),
                                MessageType = MessageType.FatalError,
                                Name = "运费合同校验",
                                PKValue = 0
                            }
                        };
                        this.OperationResult.MergeResult(operationResult);
                        e.Cancel = true;
                        return;
                    }
                }
            }
            base.BeforeExecuteOperationTransaction(e);
        }

        private object GetContract(Context ctx, string salNo)
        {
            string result = string.Empty;
            string text = $"/*dialect*/   SELECT T0.FBILLNO  FROM T_PUR_CONTRACT T0  WHERE T0.F_PXIA_SalStockBillno = '{salNo}' AND T0.FCANCELSTATUS<>'B'";
            DataSet dataSet = DBServiceHelper.ExecuteDataSet(ctx, text);
            if (dataSet.Tables[0].Rows.Count > 0)
            {
                List<string> list = new List<string>();
                foreach (DataRow row in dataSet.Tables[0].Rows)
                {
                    list.Add(row[0].ToString());
                }
                result = string.Join(",", list);
                //result = Convert.ToString(dataSet.Tables[0].Rows[0][0]);
            }
            return result;
        }

        /// <summary>
        /// 加载所有列
        /// </summary>
        /// <param name="e"></param>
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            FormMetadata meta = MetaDataServiceHelper.GetFormMetaData(this.Context, this.BusinessInfo.GetForm().Id);
            var fieldKeyList = meta.BusinessInfo.GetBosFields().Select(x => x.Field.Key).ToList();
            for (int i = 0; i < fieldKeyList.Count; i++)
            {
                e.FieldKeys.Add(fieldKeyList[i]);
            }
        }
    }
}
